<?php
namespace app\user\controller;

use app\user\model\User as modelUser;
use app\user\model\Address as modelAddress;
use app\user\model\Question as modelQuestion;
use app\user\model\Coupon as modelCoupon;
use app\user\model\Comment as modelComment;
use app\user\model\Goods as modelGoods;
use think\Controller;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;

class Person extends Controller
{
    // +----------------------------------------------------------------------
    // | 个人中心主页
    // +----------------------------------------------------------------------
    public function index()
    {
        $user = Session::get('user');
        $goodsid=Cache::smembers('user_collect_id_'.$user['id']);

        $collectgoods=db('goods')->where('id', 'in', $goodsid)->select();

        $this->assign(['user' =>$user,'collectgoods'=>$collectgoods]);
        return $this->fetch();
    }

    // +----------------------------------------------------------------------
    // | 个人信息页面和修改头像，修改信息函数
    // +----------------------------------------------------------------------
    public function toinformation()
    {
        $user = Session::get('user');
        $this->assign('user', $user);
        return $this->fetch("information");
    }
    /*修改头像*/
    public function imag()
    {
        $user = Session::get('user');
        $Name = $user->name;
        $set_user = modelUser::where('name', $Name)->find();


        $file = Request::file('picture');

        $info = $file->move('../public/static/user/uploads/picture');
        $set_user->picture = $info->getSaveName();
        $set_user->save();
        Session::delete('user');
        Session::set('user', $set_user);
        echo "<script> location.assign('/information');</script>";
    }
    /*修改信息*/
    public function setinformation()
    {
        $user = Session::get('user');
        $Name = $user->name;
        $set_user = modelUser::where('name', $Name)->find();

        $nickname = Request::post('nickname');
        if ($nickname != null) {
            $set_user->nickname = $nickname;
        }

        $gender = Request::post('gender');
        $set_user->gender = $gender;

        $birthday = Request::post('birthday');
        if ($birthday != null) {
            $set_user->birthday = $birthday;
        }

        $phone = Request::post('phone');
        if ($phone != null) {
            $set_user->phone = $phone;
        }
        $set_user->save();
        Session::delete('user');
        Session::set('user', $set_user);
        echo "<script> location.assign('/information');</script>";
    }



    // +----------------------------------------------------------------------
    // | 安全设置页面
    // +----------------------------------------------------------------------
    public function tosafety()
    {
        $user = Session::get('user');
        $this->assign('user', $user);
        return $this->fetch("safety");
    }
    /*修改密码页面*/
    public function topassword()
    {
        return $this->fetch("password");
    }
    /*修改密码*/
    public function setpass()
    {
        $user = Session::get('user');
        $Name = $user->name;
        $set_user = modelUser::where('name', $Name)->find();

        $password = Request::post('password');//原密码
        if ($set_user->pass != $password) {
            echo "<script> alert('原密码不正确，请重试！');</script>";
            echo "<script> location.assign('/password');</script>";
        } else {
            $newpass = Request::post('newpass');//新密码
            $set_user->pass = $newpass;
            $set_user->save();
            Session::delete('user');
            Session::set('user', $set_user);
            echo "<script> alert('修改密码成功，请记住您的新密码。');</script>";
            echo "<script> location.assign('/safety');</script>";
        }
    }
    /*修改邮箱页面*/
    public function toemail()
    {
        return $this->fetch("email");
    }
    /*修改邮箱*/
    public function setemail()
    {
        $email_code = Session::get('email_code');//获取后台验证码
        $code = Request::post('Code');

        if ($code != $email_code) {
            Session::delete('email_code');
            echo "<script> alert('验证码错误,请重试！');</script>";
            echo "<script> location.assign('/setemail.html');</script>";
        } else {
            $user = Session::get('user');
            $Name = $user->name;
            $set_user = modelUser::where('name', $Name)->find();
            $set_user->email = Request::post('umail');
            $set_user->save();
            Session::delete('user');
            Session::set('user', $set_user);

            Session::delete('email_code');
            echo "<script> alert('更改绑定邮箱成功！');</script>";
            echo "<script> location.assign('/safety');</script>";
        }
    }
    /*安全问题设置*/
    public function question()
    {
        return $this->fetch("question");
    }
    public function setquestion()
    {
        $user = Session::get('user');
        $question1 = Request::post('question1');
        $answer1 = Request::post('answer1');
        $question2 = Request::post('question2');
        $answer2 = Request::post('answer2');

        //清除旧问题和答案
        modelQuestion::destroy(['username'=>$user->name]);

        $newquestion1 = new modelQuestion();
        $newquestion1->username = $user->name;
        $newquestion1->question = $question1;
        $newquestion1->answer = $answer1;
        $newquestion1->save();

        $newquestion2 = new modelQuestion();
        $newquestion2->username = $user->name;
        $newquestion2->question = $question2;
        $newquestion2->answer = $answer2;
        $newquestion2->save();
        
        echo "<script> alert('设置密保问题成功！');</script>";
        echo "<script> location.assign('/safety');</script>";
    }


    // +----------------------------------------------------------------------
    // | 收货地址页面和相关函数
    // +----------------------------------------------------------------------
    public function toaddress()
    {
        $user = Session::get('user');
        $addresslist = modelAddress::where('name', $user->name)->select();//获取地址信息
        $this->assign('addresslist', $addresslist);
        return $this->fetch("address");
    }
    /*修改默认地址*/
    public function setdefault()
    {
        $user = Session::get('user');
        $add = new modelAddress;
        $id = Request::post('addressid');
        
        $address = $add->where('name', $user->name)->where('is_default', '1')->find();
        if (!empty($address)) {
            $address->is_default = 0;
            $address->save();
        }

        $setaddress = $add->where('id', $id)->find();
        $setaddress->is_default = 1;
        $setaddress->save();
    }
    /*新增地址*/
    public function newaddress()
    {
        $user = Session::get('user');

        $add = new modelAddress();
        $add->name = $user->name;
        $add->receiver = Request::post('receiver');
        $add->phone = Request::post('phone');
        $add->address = Request::post('address');
        $add->save();
        echo "<script> location.assign('/address');</script>";
    }
    /*删除地址*/
    public function deladdress()
    {
        $id = Request::post('addressid');
        modelAddress::destroy(['id'=>$id]);
    }

    // +----------------------------------------------------------------------
    // | 订单管理页面
    // +----------------------------------------------------------------------
    public function toorder()
    {
//
        //待付款
        $user = Session::get('user');
        $time=Cache::ttl('user_order_id_'.$user['id']);
        if(empty($time)){
            $time=0;
        }
        //$goodsid=Cache::smembers('user_collect_id_'.$user['id']);
        $orders=Cache::hgetall('user_order_id_'.$user['id']);
        //dump($orders);
        $arr=[];
        $total_price=0;
        foreach ($orders as $k=>$v) {
            $v=json_decode($v);
            $orderid=explode('+', $k);
            $arr[$orderid[0]][$orderid[1]]['num']=$v->num;
            $goods=db('goods')->where('id', $orderid[1])->find();
            $arr[$orderid[0]][$orderid[1]]['thumb']=$goods['thumb'];
            $arr[$orderid[0]][$orderid[1]]['goods_name']=$goods['goods_name'];
            $arr[$orderid[0]][$orderid[1]]['sale_price']=$goods['sale_price'];
            //第一件商品总价
            $arr[$orderid[0]][$orderid[1]]['total_price']=$arr[$orderid[0]][$orderid[1]]['num']*$arr[$orderid[0]][$orderid[1]]['sale_price'];
//            $total_price+=$arr[$orderid[0]][$orderid[1]]['total_price'];
            //$arr[$orderid[0]][$orderid[1]]['total_price']=$total_price;
        }

        //dump($arr);


        //待发货

        $waitsend=db('order')->where([
            'user_id'=>$user['id'],
            'is_send'=>0
        ])->select();
        $waitarr=[];
        //dump($waitsend);
        foreach ($waitsend as $k=>$v) {
            $goodid=explode(',', $v['goods_id']);
            $goodsnum=explode(',', $v['order_text']);
            $gn=[];
            foreach ($goodsnum as $k2=>$v2) {
                $namenum=explode('×', trim($v2));
                $gn[$namenum[0]]=$namenum[1];
            }
//            dump($gn);
//            die();
            foreach ($goodid as $k1=>$v1) {
                $goods=db('goods')->where('id', $v1)->find();
                $waitarr[$v['order_id']][$v1]['goods_name']=$goods['goods_name'];
                foreach ($gn as $k3=>$v3) {
                    if ($k3==$waitarr[$v['order_id']][$v1]['goods_name']) {
                        $waitarr[$v['order_id']][$v1]['num']=$v3;
                    }
                }
                $waitarr[$v['order_id']][$v1]['thumb']=$goods['thumb'];
                $waitarr[$v['order_id']][$v1]['sale_price']=$goods['sale_price'];
                $waitarr[$v['order_id']][$v1]['total_price']=$goods['sale_price']*$waitarr[$v['order_id']][$v1]['num'];
            }
        }
        //dump($waitarr);

        //待收获
        $waitget=db('order')->where([
            'user_id'=>$user['id'],
            'is_send'=>1,
            'is_sure'=>0

        ])->select();
        $getarr=[];
        //dump($waitsend);
        foreach ($waitget as $k=>$v) {
            $goodid=explode(',', $v['goods_id']);
            $goodsnum=explode(',', $v['order_text']);
            $gn=[];
            foreach ($goodsnum as $k2=>$v2) {
                $namenum=explode('×', $v2);
                $gn[$namenum[0]]=$namenum[1];
            }
            foreach ($goodid as $k1=>$v1) {
                $goods=db('goods')->where('id', $v1)->find();
                $getarr[$v['order_id']][$v1]['goods_name']=$goods['goods_name'];
                foreach ($gn as $k3=>$v3) {
                    if ($k3==$getarr[$v['order_id']][$v1]['goods_name']) {
                        $getarr[$v['order_id']][$v1]['num']=$v3;
                    }
                }
                $getarr[$v['order_id']][$v1]['thumb']=$goods['thumb'];
                $getarr[$v['order_id']][$v1]['sale_price']=$goods['sale_price'];
                $getarr[$v['order_id']][$v1]['total_price']=$goods['sale_price']*$getarr[$v['order_id']][$v1]['num'];
            }
        }

        //待评价
//        $orderids=db('order')->field('order_id')->where(['is_sure'=>1,'user_id'=>$user['id']])->select();
//        $ids=[];
//        foreach ($orderids as $k=>$v){
//            $commentsid=db('comment')->field('id')->where('order_id',$v)->select();
//
//            $ids[]=$v;
//        }
//        $comment=db('comment')->where(['order_id'=>$ids,'is_common'=>0])->select();
        $comment=db('comment')->alias('a')->field('a.*,c.thumb,c.goods_name,c.sale_price')->join('order b', "a.is_common=0 and a.order_id=b.order_id and b.is_sure=1 and a.user_id={$user['id']}")->join('goods c', 'a.goods_id=c.id')->select();

        //dump($comment);
        // die();
        $data=input('get.');
        if(!empty($data['act1'])){
            $act1=$data['act1'];$act2=0;$act3=0;$act4=0;
        }else if(!empty($data['act2'])){
            $act1=0;$act2=$data['act2'];$act3=0;$act4=0;
        }else if(!empty($data['act3'])){
            $act1=0;$act2=0;$act3=$data['act3'];$act4=0;
        }else if(!empty($data['act4'])){
            $act1=0;$act2=0;$act3=0;$act4=$data['act4'];
        }
        if(empty($data['act1'])&&empty($data['act2'])&&empty($data['act3'])&&empty($data['act4'])){
            $act1=1;$act2=0;$act3=0;$act4=0;
        }
        $this->assign(['arr'=>$arr,'waitarr'=>$waitarr,'getarr'=>$getarr,'comment'=>$comment,'time'=>$time,'act1'=>$act1,'act2'=>$act2,'act3'=>$act3,'act4'=>$act4]);
        return $this->fetch("order");
    }


    // +----------------------------------------------------------------------
    // | 评价页面
    // +----------------------------------------------------------------------
    public function tocomment()
    {
        $user = Session::get('user');
        $comment_Y = modelComment::where('user_id', $user->id)->where('is_common', 1)->order('id desc')->select();//已评价
        $comment_N = modelComment::where('user_id', $user->id)->where('is_common', 0)->order('id desc')->select();//未评价

        $this->assign('comment_Y', $comment_Y);
        $this->assign('comment_N', $comment_N);

        //return $comment[0]->goods->goods_name;
        return $this->fetch("comment");
    }

    // +----------------------------------------------------------------------
    // |消息页面
    // +----------------------------------------------------------------------
}
